<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/5/6
 * Time: 13:06
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallCart;
use app\common\model\MallCateCart;
use app\common\model\MallGoodsSku;
use think\App;

class Cart extends Base
{
    protected $model = null;

    public function __construct(App $app)
    {
        $this->model = new MallCateCart();
        parent::__construct($app);
    }

    /**
     * 添加购物车
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addToCart()
    {
        $goods_id = $this->request->param('goods_id', 0, 'intval');  //sku_id
        $openid = $this->m_openid;
        $buynum = $this->request->param('buynum', 1, 'intval');
        if ($goods_id == 0) {
            return Show::json_show(Status::mini_error, "商品信息不存在");
        }
        //查询商品是否存在
        try {
            $goodsSku = (new MallGoodsSku())->getBaseById($goods_id, 'id,goods_id,specs_value_ids,stock,image,price,is_dan', 'goods');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        if (empty($goodsSku)) {
            return Show::json_show(Status::mini_error, "规格不存在");
        }

        $goods = $goodsSku['goods'];
        if (empty($goods)) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }
        $data = array(
            'openid' => $this->m_openid,
            'goods_id' => $goods['id'],
            'shop_id' => $goods['shop_id'],
            'thumb_title' => $goods['thumb_title'],
            'total' => $buynum,
            'goods_price' => $goods['price'],
            'option_id' => $goodsSku['id']
        );
        $obj = $this->model;
        $info = $obj->getMallCartBySkuIdAndOpenidInfo($this->m_openid, $goodsSku['id']);
        $rr = 1;
        try {
            if ($info) {
                $rr = 2;
                $result = $info->save(array('total' => $info['total'] + $buynum));
            } else {
                $result = $obj->save($data);
            }
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询错误");
        }
        if ($result) {
            return Show::json_show(Status::mini_normal, 'ok', ["rr" => $rr]);
        } else {
            return Show::json_show(Status::mini_error, "添加失败");
        }
    }

    /**
     * 获取购物车数量
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCartNum()
    {
        $res = $this->model->field('count(*) as count')
            ->where('shop_id',$this->shop_id)
            ->where('openid', $this->m_openid)
            ->find();
        return Show::json_show(Status::mini_normal, 'ok', [
            "cartNum" => $res['count'] ?? '',
        ]);
    }

    /**
     * 获取购物车列表
     * @return array|\think\response\Json
     */
    public function getCartListInfo()
    {
        try {
            $result = $this->model->getMallCartByOpenidInfo($this->m_openid,$this->shop_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, 'ok', $result);
    }

    /**
     * 修改数量
     * @return array|\think\response\Json
     * @throws \think\Exception
     */
    public function setCartNumber()
    {
        $cart_id = $this->request->param('cart_id', 0, 'intval');
        $number = $this->request->param('number', 0, 'intval');
        if ($cart_id == 0 || $number == 0) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        try {
            $cart = $this->model->getBaseById($cart_id, 'id,option_id,total', 'goodsSku');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        if (empty($cart)) {
            return Show::json_show(Status::mini_error, "订单错误");
        }

        if (empty($cart['goodsSku'])) {
            return Show::json_show(Status::mini_error, "商品不存在");
        }
        $goods = $cart['goodsSku'];
        if ($number > $goods['stock']) {
            return Show::json_show(Status::mini_error, "库存超量");
        }
        $res = $this->model->updateDataSave($cart_id, [
            "total" => $number,
            "update_time" => time()
        ]);
        if ($res) {
            return Show::json_show(Status::mini_normal, "ok");
        } else {
            return Show::json_show(Status::mini_error, "修改失败");
        }

    }

    /**
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delCartInfo()
    {
        $cart_id = $this->request->param('id', 0, 'intval');
        if ($cart_id == 0) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        try {
            $row = $this->model->getBaseById($cart_id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        if (empty($row)) {
            return Show::json_show(Status::mini_error, "订单错误");
        }
        $res = $this->model->destroy($cart_id, true);
        if ($res) {
            $num = $this->model->field('sum(total) as total')->where('openid',$this->m_openid)->where('goods_id',$row['goods_id'])->find();
            return Show::json_show(Status::mini_normal, "ok",[
                "num"=>$num['total'] ?? 0
            ]);

        } else {
            return Show::json_show(Status::mini_error, "删除失败");
        }
    }

    /**
     * 清空购物车
     * @return array|\think\response\Json
     */
    public function setClearCart()
    {
        try {
            $res = $this->model
                ->where('openid', $this->m_openid)
                ->select()->toArray();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        if (empty($res)) {
            return Show::json_show(Status::mini_error, "没有商品");
        }
        $result = $this->model->destroy(array_column($res, 'id'), true);
        if ($result) {
            return Show::json_show(Status::mini_normal, "清空成功");
        } else {
            return Show::json_show(Status::mini_error, "清空失败");
        }
    }
}